package org.wxd.common.utils;

import com.google.common.collect.Maps;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;

/**
 * Created by wangxd on 2016/12/9.
 */
public final class ConfigurationUtil {

    private static Map<String, Map<String, String>> FILE_MAP = Maps.newLinkedHashMap();

    private ConfigurationUtil() {

    }

    /**
     * 获取文件的配置信息
     *
     * @param filePath
     * @return
     */
    public static Map<String, String> getAllOfFile(String filePath) {
        return isNotLoadBuildMap(filePath);
    }

    private static Map<String, String> isNotLoadBuildMap(String filePath) {
        Map<String, String> pMap = FILE_MAP.get(filePath);
        if (pMap != null && !pMap.isEmpty()) return pMap;
        InputStream is = ConfigurationUtil.class.getClassLoader().getResourceAsStream(filePath);
        if (is == null) return Collections.EMPTY_MAP;
        Properties props = new PropertiesOrdered();
        try {
            props.load(new InputStreamReader(is,"UTF-8"));
            toFileMap(props, filePath);
            return isNotLoadBuildMap(filePath);
        } catch (IOException e) {
            throw new ConfigurationException(e.getMessage(), e);
        }
    }

    /**
     * 根据文件名称获取值
     *
     * @param filePath 如果classes目录下的则直接写文件名
     * @param key
     * @return
     */
    public static String get(String filePath, String key) {
        if (!StringUtil.isNotBlank(filePath) || !StringUtil.isNotBlank(key)) return null;
        return isNotLoadBuildMap(filePath).get(key);
    }


    /**
     * 将配置文件数据放入FILE_MAP中进行缓存
     *
     * @param props
     * @param filePath
     */
    private static void toFileMap(Properties props, String filePath) {
        Map<String, String> maps = Maps.newLinkedHashMap();
        props.keySet().forEach(p -> maps.put((String) p, props.get(p).toString()));
        FILE_MAP.put(filePath, maps);
    }


    public static class ConfigurationException extends RuntimeException {
        public ConfigurationException() {
            super();
        }

        public ConfigurationException(String message) {
            super(message);
        }

        public ConfigurationException(String message, Throwable cause) {
            super(message, cause);
        }

        public ConfigurationException(Throwable cause) {
            super(cause);
        }

    }
}
